package com.zx.tradeclient.ctrl.index2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.zx.base.ctrl.BaseActivity;
import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.ActivityTaskManager;
import com.zx.base.widget.ExpanderDialog;
import com.zx.base.widget.ExpanderDialog.DialogListener;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.base.widget.QuitDialog;
import com.zx.tradeclient.R;
import com.zx.tradeclient.adapter.HomePageRankingAdapter;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.ctrl.SearchActivity;
import com.zx.tradeclient.entity.GoodsInfo;

public class Index2Activity extends BaseActivity implements OnClickListener {

	private Button header_left, header_right;
	private HomePageRankingAdapter adapter;
	private ArrayList<GoodsInfo> list_info = new ArrayList<GoodsInfo>();
	private TradeApp app;

	private LoadMoreListViewWithProgress viewWhitProgress;
	private LoadMoreListView listView;
	private int currentPage;
	private int totalPage;
	private int perPageCount = 14;
	private LinearLayout linear;
	private ExpanderDialog expander;
	private ImageLoader imageLoader;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				loadDataTask();
				break;
			case 1:
				adapter.notifyDataSetChanged();
				break;
			case 2:

				Toast toast2 = Toast.makeText(Index2Activity.this, "无反应",
						Toast.LENGTH_SHORT);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;
			case 3:
				break;

			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index2);

		if (!(ActivityTaskManager.getInstance().containsName("Index2Activity"))) {
			ActivityTaskManager.getInstance().putActivity("Index2Activity",
					this);
		}

		init();
	}

	private void init() {

		app = (TradeApp) getMyApplication();

		imageLoader = app.imageLoader;

		header_left = (Button) findViewById(R.id.header_left);
		header_left.setBackgroundResource(R.drawable.header_dquery);
		header_left.setOnClickListener(this);

		header_right = (Button) findViewById(R.id.header_right);
		header_right.setBackgroundResource(R.drawable.header_dnone);
		header_right.setText("等级");
		header_right.setOnClickListener(this);

		linear = (LinearLayout) findViewById(R.id.index2_main_layout);

		adapter = new HomePageRankingAdapter(Index2Activity.this, list_info,
				app.imageLoader);

		viewWhitProgress = new LoadMoreListViewWithProgress(this);
		listView = viewWhitProgress.getListView();

		listView.setDivider(getResources().getDrawable(R.drawable.divider));
		listView.setSelector(getResources().getDrawable(
				R.drawable.list_item_colorexchange));
		listView.setDividerHeight(2);
		listView.setAdapter(adapter);
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				loadDataTask();
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (((TradeApp) getApplicationContext()).isNetWorkConnection) {

					Intent intent = new Intent(Index2Activity.this,
							SupplyInfoActivity.class);
					intent.putExtra("productid", list_info.get(position).getGoods_id());
					startActivity(intent);

				} else {
					Toast toast2 = Toast.makeText(Index2Activity.this,
							"网络连接断开，请检查网络", Toast.LENGTH_SHORT);
					toast2.setGravity(Gravity.CENTER, 0, 0);
					toast2.show();
				}

			}
		});

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		int height = metric.heightPixels;
		float px = 64 * (metric.densityDpi / 160f);
		perPageCount = (int) Math.ceil(height / px);

		linear.addView(viewWhitProgress);

		Message msg0 = new Message();
		msg0.what = 0;
		handler.sendMessage(msg0);

	}

	private void loadDataTask() {

		currentPage = currentPage + 1;
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "supplyDemandList");
		map.put("way", "11");
		if (app.product_rating.getCategory_id() != "") {
			map.put("cityId", app.product_rating.getCategory_id());
		}
		if (app.product_rating.getCategory_id() != "") {
			map.put("productTypeMin", app.product_rating.getCategory_id());
		}
		map.put("currentPage", String.valueOf(currentPage));
		map.put("rowCountPerPage", perPageCount + "");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				try {
					String succeed = response.getString("succeed");
					if (succeed.equals("000")) {
						JSONObject userData = response;
						currentPage = userData.getInt("currentPage");
						totalPage = userData.getInt("totalPage");
						if (currentPage == totalPage) {
							listView.loadComplete(false);
						} else {
							listView.loadComplete(true);
						}

						JSONArray jsonArray = new JSONArray(userData
								.getString("dataList"));
						for (int i = 0; i < jsonArray.length(); i++) {
							JSONObject jsonObject = jsonArray.getJSONObject(i);

							GoodsInfo good = new GoodsInfo();

							good.setGoods_id(jsonObject.getString("id"));
							good.setGoods_name(jsonObject
									.getString("productname"));
							good.setGoods_price(jsonObject.getString("price"));
							good.setGoods_number(jsonObject.getString("num"));
							good.setGoods_site(jsonObject.getString("location"));
							good.setGoods_phone(jsonObject.getString("mobile"));
							String date = jsonObject.getString("createtime");
							if ((date == null) || (date.equals(""))) {
								date = "";
							}
							if (date.length() > 10) {
								date = date.substring(0, 10);
							}
							good.setGoods_date(date);
							good.setGoods_number_type(jsonObject
									.getString("way"));
							// 添加内容
							list_info.add(good);
						}

					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

				// We need notify the adapter that the data have been changed
				adapter.notifyDataSetChanged();
				viewWhitProgress.show();

			}

			@Override
			public void onFailure(Throwable e) {
				// TODO Auto-generated method stub

			}
		});

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == header_left) {
			Intent intent = new Intent(Index2Activity.this,
					SearchActivity.class);
			intent.putExtra("index", "2");
			startActivity(intent);
		} else if (v == header_right) {

			expander = new ExpanderDialog(Index2Activity.this,
					new DialogListener() {

						@Override
						public void endme(String group, String value,
								int groupid, int valueid) {
							//
							header_right.setText(group + " " + value);
							app.product_rating
									.setCategory_id(app.cityids[groupid][valueid]);
							app.product_rating.setCategory_name(value);

							list_info.clear();
							currentPage = 0;
							totalPage = 0;
							perPageCount = 10 /* (int) Math.ceil(height / px) */;
							viewWhitProgress.loading();
							loadDataTask();
						}
					}, 1);
			expander.show();
			/*
			 * Intent intent = new Intent(Index3Activity.this,
			 * CategoryActivity.class); intent.putExtra("categ", "1");
			 * startActivity(intent);
			 */

		} 

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (Constant.debug)
				Log.d("TMG", "ManageActivity KEYCODE_BACK");
			QuitDialog dialog = new QuitDialog(Index2Activity.this);
			dialog.exitConfirm();

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}